package View.acao;

import Data.ClienteDAO;
import Model.ClienteBean;
import java.sql.Date;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JOptionPane;

public class CadastrarCliente extends javax.swing.JInternalFrame {

    private ClienteBean cliente_a_ser_alterado = null;

    public CadastrarCliente(ClienteBean cliente) {
        this.cliente_a_ser_alterado = cliente;
        initComponents();
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

        if (cliente != null) {
            jtf_email.setText(cliente.getEmail());
            jtf_endereco.setText(cliente.getEnderenço());
            jtf_nome.setText(cliente.getCliente_nome());
            jtf_telefone.setText(cliente.getTelefone());
            jftf_cpf.setValue(cliente.getCpf());
            if (!(cliente.getData_nascimento() == null)) {
                jftf_datanascimento.setValue(sdf.format(cliente.getData_nascimento()));
            }
        }
    }

    private void limparCampos() {
        jtf_nome.setText("");
        jtf_email.setText("");
        jtf_endereco.setText("");
        jtf_telefone.setText("");
        jftf_cpf.setValue(null);
        jftf_datanascimento.setValue(null);
    }

    private boolean validar() {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        sdf.setLenient(false);
        try {
            sdf.parse(jftf_datanascimento.getText());
        } catch (ParseException ex) {
            JOptionPane.showMessageDialog(rootPane, "Data invalida!");
            return false;
        }


        if (jtf_nome.getText().isEmpty()) {
            JOptionPane.showMessageDialog(rootPane, "Preencha o nome");
            return false;
        }

        if (!jftf_cpf.isEditValid()) {
            JOptionPane.showMessageDialog(rootPane, "Preencha corretamente o CPF");
            return false;
        }

        if (!jftf_datanascimento.isEditValid()) {
            JOptionPane.showMessageDialog(rootPane, "Preencha a data de nascimento corretamente");
            return false;
        }

        if (jtf_telefone.getText().isEmpty() || jtf_telefone.getText().length() < 8) {
            JOptionPane.showMessageDialog(rootPane, "Telefone invalido");
            return false;
        }

        if (jtf_email.getText().isEmpty()) {
            JOptionPane.showMessageDialog(rootPane, "Email invalido");
            return false;
        }

        if (jtf_endereco.getText().isEmpty()) {
            JOptionPane.showMessageDialog(rootPane, "Endereço invalido");
            return false;
        }

        return true;
    }

    private void performAction() {
        if (validar()) {
            ClienteDAO data = new ClienteDAO();

            if (cliente_a_ser_alterado != null) {
                cliente_a_ser_alterado.setCliente_nome(jtf_nome.getText());
                cliente_a_ser_alterado.setCpf(jftf_cpf.getText());
                cliente_a_ser_alterado.setEmail(jtf_email.getText());
                cliente_a_ser_alterado.setEnderenço(jtf_endereco.getText());
                cliente_a_ser_alterado.setTelefone(jtf_telefone.getText());
                cliente_a_ser_alterado.setData_nascimento(pegarDate(jftf_datanascimento.getText()));
                if (cliente_a_ser_alterado.getData_nascimento() == null) {
                    return;
                }

                try {

                    if (data.atualizarCliente(cliente_a_ser_alterado)) {
                        JOptionPane.showMessageDialog(rootPane, "Cliente atualizado com sucesso!");
                        this.dispose();
                    } else {
                        throw new SQLException("ERro ao atualizar cliente");
                    }
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(rootPane, "Erro: \n" + ex.getMessage());
                }

            } else {
                ClienteBean cliente = new ClienteBean();

                cliente.setCliente_nome(jtf_nome.getText());
                cliente.setCpf(jftf_cpf.getText());
                cliente.setEmail(jtf_email.getText());
                cliente.setEnderenço(jtf_endereco.getText());
                cliente.setTelefone(jtf_telefone.getText());
                cliente.setData_nascimento(pegarDate(jftf_datanascimento.getText()));

                if (cliente.getData_nascimento() == null) {
                    return;
                }
                try {
                    if (data.cadastrarCliente(cliente)) {
                        JOptionPane.showMessageDialog(rootPane, "Cliente cadastrado com sucesso!");
                        limparCampos();
                    } else {
                        throw new SQLException("Ocorreu algum erro ao cadastrar o cliente");
                    }
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(rootPane, "Erro: \n" + ex.getMessage());
                }
            }

        }
    }

    private Date pegarDate(String data) {
        String[] dataquebrada = data.split("/");

        Date objdata = null;
        try {
            Calendar calendario = Calendar.getInstance();
            calendario.set(Integer.parseInt(dataquebrada[2]), Integer.parseInt(dataquebrada[1]) - 1, Integer.parseInt(dataquebrada[0]));
            objdata = new java.sql.Date(calendario.getTimeInMillis());
        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, "Erro ao converter data");
            return null;
        }
        return objdata;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jtf_nome = new javax.swing.JTextField();
        jftf_cpf = new javax.swing.JFormattedTextField();
        jtf_telefone = new javax.swing.JTextField();
        jtf_email = new javax.swing.JTextField();
        jtf_endereco = new javax.swing.JTextField();
        jftf_datanascimento = new javax.swing.JFormattedTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setTitle("Cadastro de Cliente");
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosing(evt);
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameOpened(evt);
            }
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameActivated(evt);
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
        });

        jLabel1.setText("Nome:");

        jLabel2.setText("CPF:");

        jLabel3.setText("Data Nascimento:");

        jLabel4.setText("Telefone:");

        jLabel5.setText("E-mail:");

        jLabel6.setText("Endereço:");

        try {
            jftf_cpf.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        try {
            jftf_datanascimento.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6))
                .addGap(53, 53, 53)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jtf_nome)
                    .addComponent(jftf_cpf, javax.swing.GroupLayout.DEFAULT_SIZE, 348, Short.MAX_VALUE)
                    .addComponent(jtf_telefone)
                    .addComponent(jtf_email)
                    .addComponent(jtf_endereco)
                    .addComponent(jftf_datanascimento))
                .addContainerGap(31, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jtf_nome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jftf_cpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jftf_datanascimento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jtf_telefone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jtf_email, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(jtf_endereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jButton1.setText("OK");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Cancelar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(26, 26, 26)
                .addComponent(jButton2)
                .addGap(36, 36, 36))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton1, jButton2});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 63, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
    }//GEN-LAST:event_formWindowActivated

    private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameOpened
    }//GEN-LAST:event_formInternalFrameOpened

    private void formInternalFrameActivated(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameActivated
    }//GEN-LAST:event_formInternalFrameActivated

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
    }//GEN-LAST:event_formInternalFrameClosing

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        performAction();

    }//GEN-LAST:event_jButton1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JFormattedTextField jftf_cpf;
    private javax.swing.JFormattedTextField jftf_datanascimento;
    private javax.swing.JTextField jtf_email;
    private javax.swing.JTextField jtf_endereco;
    private javax.swing.JTextField jtf_nome;
    private javax.swing.JTextField jtf_telefone;
    // End of variables declaration//GEN-END:variables
}
